<?php
	header('content-type:text/html;charset=utf-8');
	date_default_timezone_set("Asia/Chongqing");
	require('../class/autoload.php');
	session_start();

	/*
		### 验证来路路径是否合法

	*/
	$uri = parse_url(@$_SERVER["HTTP_REFERER"])['path'];
	$uris = array(
	  '/yunpan/before/login.html',
	  '/yunpan/before/main.html',
	  '/yunpan/before/password.html',
	  '/yunpan/after/password.html',
	  '/yunpan/before/register.html',
	  '/yunpan/before/share_all.html',
	  '/yunpan/before/share_me.html',
	);
	if(!in_array($uri,$uris)){
	 	exit('10004');
	}



	/*
		### 获取验证码图片
		http://www.yunpan.top/interface/before_interface.php?type=code
	*/
	if($_REQUEST['type'] == 'code'){
		require_once "../class/plugin/vcode.class.php";
		Code\VCode::GetCode();
		exit;
	}

	//需要验证验证码的请求
	$vcode_arr = array(
		'register',
		'changePassword',
	);
	if(in_array($_REQUEST['type'],$vcode_arr)){
		require_once "../class/plugin/vcode.class.php";
		$vcode = I('vcode','p');
		if(!Code\VCode::Check_Code($vcode)){
			exit('10003');	//验证码不正确
		}
	}


	//验证用户名
	$account = intval(I('account'));
	if(!$account){
		if($_REQUEST['type'] != '_getShareAllList'){
			if($uri != '/yunpan/before/share_all.html'){
				exit('10001');
			}
		}
	}
	$account_arr = array(	//跳过验证用户名与seisson的项
		'login',
		'register',
		'_getShareAllList'
	);
	if(!in_array($_REQUEST['type'],$account_arr)){
		if($account != @$_SESSION['account']){
                       if($uri != '/yunpan/before/share_all.html'){
			   exit('100011');
                       }
		}
	}

	$token_arr = array(		//跳过token验证的项
		'login',
		'download',
		'register',
		'_getShareAllList'
	);
	if(!in_array($_REQUEST['type'],$token_arr)){
		$token1 = I('token1');
		if(!VerifyToken1($account,$token1,1)){		 	//验证token

                         if($uri != '/yunpan/before/share_all.html'){
      			   exit('10002');
 
                         }
		}
	}



	$tokenv_arr = array(		//跳过获取token的项
		'download',
		'_getShareAllList' 
	);

        if($uri != '/yunpan/before/share_all.html'){
	   if(!in_array($_REQUEST['type'],$tokenv_arr)){
		$tmp_arr = array(
			'token1'=>SetToken1($account,1)
		);
	   }
        }





	switch ($_REQUEST['type']) {

		default :
			echo 'default';
			dump($_FILES);
			dump($_REQUEST,1);
			break;




		//移动文件或目录
		case '_moveFileTo':
			$moveId = intval(I('moveId','p'));
			$moveToId = intVal(I('moveToId','p'));
			_checkVal($moveId);//检测变量
			$pdo = MyPdo2::init();
			$sql = "update file_list set parent = ? where id = ? and account = ?";
			$res = $pdo->dml($sql,array($moveToId,$moveId,$account));
			if($res){
				$tmp_arr['stat'] = 'ok';
				_deleteFileListCahce($account);	//删除文件列表缓存
			}else{
				$tmp_arr['stat'] = 'err2';
			}
			exit(json_encode($tmp_arr));
			break;




		//获取可移动的目录列表
		case '_getMoveDirList':
			$pdo = MyPdo2::init();
			$sql = "select id,fname,parent from file_list where account = ? and type = 'dir'";
			$res = $pdo->dql($sql,array($account));
			if(!$res){
				$tmp_arr['stat'] = 'err2';	//没有目录
				exit(json_encode($tmp_arr));
			}

			$list = array();
			foreach($res as $k=>$v){
				if($v['parent'] == 0){
					if(!isset($list[0])){
						$list[0]['sub'] = array($res[$k]);
					}else{
						$list[0]['sub'][] = $res[$k];
					}
				}
			}

			$parent_arr = array();
			foreach($res as $v){
				if(!in_array($v['parent'],$parent_arr)){
					$parent_arr[$v['parent']] = array();
				}
			}
			foreach($res as $v){
				$parent_arr[$v['parent']]['data'][] = $v;
				$parent_arr[$v['parent']]['stat'] = true;
			}
			$tmp_arr['data'] = $parent_arr;
			exit(json_encode($tmp_arr));
			break;




		//删除指定缓存
		case 'delCache':
 			$path = I('path','p');
			_checkVal($path);//检测变量
			if(file_exists($path)){
				unlink($path);
			}
			$tmp_arr['stat'] = 'ok';
			exit(json_encode($tmp_arr));
			break;



		//获取全部共享文件列表
		case '_getShareAllList':
			$pnow = intval(I('pnow','p'));
			$pnow = $pnow > 0 ? $pnow:1;
			$searchInp = I('searchInp','p');
			$searchSel = I('searchSel','p');
			_checkVal($searchSel);//检测变量

			$pdo = MyPdo2::init();
			$limit = 10;
			$limit_start = ($pnow - 1) * $limit;

			if(@$searchInp){
				_checkVal($searchInp);//检测变量
				if($searchSel == 'name'){			//按用户名搜索
					$sql = "select f.id,f.fname,f.path,f.size,f.ctime,u.name from file_list as f left join user_list as u on f.account = u.account where f.share = 'yes' and u.name like ? limit {$limit_start},{$limit}";
					$arr_parm = array("{$searchInp}%");
				}else if($searchSel == 'number'){	//按工号搜索
					$sql = "select f.id,f.fname,f.path,f.size,f.ctime,u.name from file_list as f left join user_list as u on f.account = u.account where f.share = 'yes' and u.account = ? limit {$limit_start},{$limit}";
					$arr_parm = array($searchInp);
				}else{								//按文件名搜索
					$sql = "select f.id,f.fname,f.path,f.size,f.ctime,u.name from file_list as f left join user_list as u on f.account = u.account where f.share = 'yes' and f.fname like ? limit {$limit_start},{$limit}";
					$arr_parm = array("{$searchInp}%");
				}
			}else{
				$sql = "select f.id,f.fname,f.path,f.size,f.ctime,u.name from file_list as f left join user_list as u on f.account = u.account where f.share = 'yes' limit {$limit_start},{$limit}";
				$arr_parm = array($account);
			}

			$res = $pdo->dql($sql,$arr_parm);
			if($res){
				$tmp_arr['data'] = $res;
			}else{
				$tmp_arr['data'] = array();	//操作失败！
			}
			$tmp_arr['expire'] = time()+ 10;
			$jsonStr = json_encode($tmp_arr);
			if(@$searchInp){
				$cachePath = '../cache/share_all/'.$searchInp.$searchSel.$pnow;
			}else{
				$cachePath = '../cache/share_all/'.$pnow;
			}
			mkdirs(dirname($cachePath));
			file_put_contents($cachePath, $jsonStr);
			exit($jsonStr);
			break;




		//下载文件
		case 'download':
			$path = I('path');

			$agent = $_SERVER['HTTP_USER_AGENT'];
			if(strpos($agent, "MSIE")){		//是IE浏览器
				$fname = iconv('utf-8','gbk',I('fname'));
			}else{
				$fname = I('fname');
			}

			_checkVal($path);//检测变量

			$file_name= iconv('utf-8','gbk','..'.$path);   //关联一个要下载的文件
			//$file_name2 = substr($file_name,strripos($file_name,'/')+1);
			if(!file_exists($file_name)){	//如果此文件不存在，则显示下面信息，并结束！
				_backBeForeOrAlert('','文件不存在！');
			}
			$fp = fopen($file_name,'r');	//打开这个文件
			$file_size=filesize($file_name);	//读取这个文件的大小
			header("Content-Type: application/octet-stream"); //设置下载文件类型
			header("Content-Ranges: bytes");		//设置字节类型（字节）
			header("Content-Length: $file_size");		//设置下载文件的大小
			//header("Accept-Ranges: bytes");		//设置字节类型（字节）
			//header("Accept-Length: $file_size");		//设置下载文件的大小
			header("Content-Disposition: attachment; filename=$fname"); //设置文件名，可指定！
			$buffer=1024;	//设置文件下载时每次读取量的大小。
			while(!feof($fp)){	//如果文件没有读取结束
				echo fread($fp,$buffer);	//当前读取量是多少
			}	
			fclose($fp);	//下载完成，关闭文件。
			_backBeForeOrAlert('','下载完成！');
		break;



		//获取我的共享文件列表
		case 'getMeShareList':
			$pdo = MyPdo2::init();
			$sql = "select id,fname,path,size,ctime from file_list where account = ? and share = 'yes'";
			$res = $pdo->dql($sql,array($account));
			if($res){
				$tmp_arr['data'] = $res;
			}else{
				$tmp_arr['data'] = array();	//操作失败！
			}
			$cachePath = '../cache/share_me/'.$account;
			mkdirs(dirname($cachePath));
			$jsonStr = json_encode($tmp_arr);
			file_put_contents($cachePath, $jsonStr);
			exit($jsonStr);
			break;



		//获取用户的使用总量
		case 'getUseCapacity':
			$pdo = MyPdo2::init();
			$sql = "select sum(size) as size from file_list where account = ?";
			$res = $pdo->dql($sql,array($account),1);
			if($res){
				$tmp_arr['ucapacity'] = floatval($res['size']);
			}else{
				$tmp_arr['ucapacity'] = 0;
			}
			$_SESSION['ucapacity'] = $tmp_arr['ucapacity'];
			$cachePath = '../cache/capacity/'.$account;
			mkdirs(dirname($cachePath));
			$jsonStr = json_encode($tmp_arr);
			file_put_contents($cachePath,$jsonStr);
			exit($jsonStr);
			break;




		//共享文件
		case 'shareFile':
			$fid = intval(I('fid','p'));
			$stype = intval(I('stype','p'));
			$pdo = MyPdo2::init();
			if($stype){	//删除文件共享
				$share_stat = 'no';
			}else{	//共享文件
				$share_stat = 'yes';
			}
			$sql2 = "update file_list set share = '{$share_stat}' where account = ? and id = ?";
			$res2 = $pdo->dml($sql2,array($account,$fid));
			if($res2){
				$tmp_arr['stat'] = 'ok';
				_deleteFileListCahce($account);	//删除文件列表缓存
			}else{
				$tmp_arr['stat'] = 'err2';	//操作失败！
			}
			exit(json_encode($tmp_arr));
			break;





		//删除文件或目录
		case 'delFile':
			$ftype = I('ftype','p');
			$path = I('path','p');
			$fid = intval(I('fid','p'));
			_checkVal($ftype,$fid,$path);//检测变量
			$pdo = MyPdo2::init();
			if($ftype == 'dir'){	//删除目录
				$sql1 = "select id from file_list where account = ? and parent = ? limit 1";
				$res1 = $pdo->dql($sql1,array($account,$fid));
				if($res1){
					$tmp_arr['stat'] = 'err3';	//目录不为空！
				}else{
					$sql2 = "delete from file_list where account = ? and id = ? and type = 'dir'";
					$res2 = $pdo->dml($sql2,array($account,$fid));
					if($res2){
						$tmp_arr['stat'] = 'ok';
						_deleteFileListCahce($account);	//删除文件列表缓存
					}else{
						$tmp_arr['stat'] = 'err2';	//删除失败！
					}
				}
				exit(json_encode($tmp_arr));
			}else{	//删除文件
				$fullPath = '..'.$path;
				if(file_exists($fullPath)){
					unlink($fullPath);
				}
				if(!file_exists($fullPath)){
					$sql = "delete from file_list where account = ? and type = 'file' and id = ?";
					$res = $pdo->dml($sql,array($account,$fid));
					if($res){
						$tmp_arr['stat'] = 'ok';
						_deleteFileListCahce($account);	//删除文件列表缓存
					}else{
						$tmp_arr['stat'] = 'err2';	//删除失败！
					}
				}else{
					$tmp_arr['stat'] = 'err2';	//删除失败！
				}
				exit(json_encode($tmp_arr));
			}
			break;





		//多选删除文件
		case 'delSelect':
			$idStr = I('idStr','p');
			_checkVal($idStr);//检测变量
			$dataArr=json_decode($idStr);
			if(count($dataArr) > 0){
				$chars = '';
				$idArr = array();
				foreach($dataArr as $v){
					$path = '..'.$v[1];
					if(file_exists($path)){
						unlink($path);
					}
					if(!file_exists($path)){
						$chars .= '?,';
						$idArr[] = $v[0];
					}
				}
				$chars = trim($chars,',');
				array_unshift($idArr,$account);

				$pdo = MyPdo2::init();
				$sql = "delete from file_list where account = ? and id in(".$chars.")";
				$res = $pdo->dml($sql,$idArr);
				if($res){
					$tmp_arr['stat'] = 'ok';
					_deleteFileListCahce($account);	//删除文件列表缓存
				}else{
					$tmp_arr['stat'] = 'err2';	//操作失败！
				}
			}else{
				$tmp_arr['stat'] = 'err3';	//操作失败！
			}
			exit(json_encode($tmp_arr));
			break;



		/*
			### 多选删除共享
			stype bool 	
				true : 添加共享
				flase: 删除共享
		*/
		case 'selectShare':
			$idStr = I('idStr','p');
			$stype = I('stype','p');
			_checkVal($idStr);//检测变量
			$dataArr=json_decode($idStr);
			$chars = '';
			$idArr = array();
			foreach($dataArr as $v){
					$chars .= '?,';
					$idArr[] = $v;
			}
			if(count($idArr) > 0){
				$chars = trim($chars,',');
				array_unshift($idArr,$account);

				$pdo = MyPdo2::init();
				//$sql = "delete from file_list where account = ? and id in(".$chars.")";
				$sql = "update file_list set share='no' where account = ? and id in(".$chars.")";
				$res = $pdo->dml($sql,$idArr);
				if($res){
					$tmp_arr['stat'] = 'ok';
					_deleteFileListCahce($account);
				}else{
					$tmp_arr['stat'] = 'err2';	//操作失败！
				}
			}else{
				$tmp_arr['stat'] = 'err3';	//操作失败！
			}
			exit(json_encode($tmp_arr));
			break;









		/*
			###文件上传
				'err2';	//没有文件上传
				'err3';	//上传的文件已存在！
		*/
		case 'upload':
			$dirId = intval(I('dirId','p'));
			$agent = $_SERVER['HTTP_USER_AGENT'];
	
			$pdo = MyPdo2::init();

			$capacity = floatval($_SESSION['capacity']);
			$ucapacity = floatval($_SESSION['ucapacity']);
			$ulimit = floatval($_SESSION['ulimit']);

			_deleteFileListCahce($account);	//删除文件列表缓存

			if(strpos($agent, "MSIE")){		//是IE浏览器
				if(!$_FILES['upFile']['size']){	//没有文件上传，返回
					_backBeForeOrAlert($tmp_arr['token1'],'请选择上传文件！');
				}
				$fname = $_FILES["upFile"]['name'];
				$fname = str_replace(' ','_',$fname);

				if(!_checkChar($fname,1)){
					$tmp_arr['stat'] = 'err6';	//非法字符！
					_backBeForeOrAlert($tmp_arr['token1'],'非法字符！');
				}

				$size = floatval($_FILES["upFile"]['size']);
				$tmp = $_FILES["upFile"]['tmp_name'];

				//检测文件大小是否超限
				if($size > $ulimit){
					_backBeForeOrAlert($tmp_arr['token1'],'上传文件大小超限！');
				}

				//检测文件总容量是否超限
				if($ucapacity + $size > $capacity){
					_backBeForeOrAlert($tmp_arr['token1'],'文件总容量超限！');
				}

				$sqlCheck = "select id from file_list where account = ? and parent = ? and fname = ? limit 1";

				$resCheck = $pdo->dql($sqlCheck,array($account,$dirId,$fname),1);
				if($resCheck){
					_backBeForeOrAlert($tmp_arr['token1'],'文件已存在！');
				}


				
				//$filePath = '../data/'.$account.'/'.$fname;
				$filePath = '../data/'.$account.'/'.md5(microtime().rand(1,999999));
				$filePath2 = iconv('utf-8','gbk',$filePath);
				if(file_exists($filePath2)){
					$filePath = '../data/'.$account.'/'.substr(md5(rand(1,99999).microtime()),5,15).'/'.$fname;
					$filePath2 = iconv('utf-8','gbk',$filePath);
				}

				//检测并创建上级目录
				mkdirs(dirname($filePath2));
			
				if(is_uploaded_file($tmp)){
					if(move_uploaded_file($tmp,$filePath2)){
						$savePath = trim($filePath,'.');
						$sql = "insert into file_list values(null,?,?,'file',?,?,?,?,'no')";
						$res = $pdo->dml($sql,array($account,$dirId,$savePath,$fname,time(),$size));
						if($res){
							_backBeForeOrAlert($tmp_arr['token1'],'文件上传成功！');
							$_SESSION['ucapacity'] = floatval($_SESSION['ucapacity']) + $size;
						}
					}
				}
				_backBeForeOrAlert($tmp_arr['token1'],'文件上传失败！');
			}else{							//非IE浏览器
				if(!count($_FILES)){	//没有文件上传，返回
					$tmp_arr['stat'] = 'err2';	//没有文件上传
					exit(json_encode($tmp_arr));
				}

				$usize = floatval(0);
				foreach($_FILES as $k=>$v){
					if(!_checkChar($v['name'],1)){
						$tmp_arr['stat'] = 'err6';	//非法字符！
						exit(json_encode($tmp_arr));
					}
					$usize += $v['size'];
				}

				//检测文件大小是否超限
				if($usize > $ulimit){
					$tmp_arr['stat'] = 'err4';	//上传文件大小超限！
					exit(json_encode($tmp_arr));
				}

				//检测文件总容量是否超限
				if($ucapacity + $usize > $capacity){
					$tmp_arr['stat'] = 'err5';	//文件总容量超限！
					exit(json_encode($tmp_arr));
				}


				$stat_arr=array();
				foreach($_FILES as $k=>$v){
					$fname = str_replace(' ','_',$v['name']);
					$sqlCheck = "select id from file_list where account = ? and parent = ? and fname = ? limit 1";
					$resCheck = $pdo->dql($sqlCheck,array($account,$dirId,$fname),1);
					if($resCheck){
						$tmp_arr['stat'] = 'err3';	//上传的文件已存在！
						exit(json_encode($tmp_arr));
					}

					//$filePath = '../data/'.$account.'/'.$fname;
					$filePath = '../data/'.$account.'/'.md5(microtime().rand(1,999999));
					$filePath2 = iconv('utf-8','gbk',$filePath);
					if(file_exists($filePath2)){
						$filePath = '../data/'.$account.'/'.md5(microtime().rand(1,999999));
						$filePath2 = iconv('utf-8','gbk',$filePath);
					}

					//检测并创建上级目录
					mkdirs(dirname($filePath2));
				
					if(is_uploaded_file($v['tmp_name'])){
						if(move_uploaded_file($v['tmp_name'],$filePath2)){
							array_push($stat_arr,array($fname,'ok'));
							$savePath = trim($filePath,'.');
							$sql = "insert into file_list values(null,?,?,'file',?,?,?,?,'no')";
							$res = $pdo->dml($sql,array($account,$dirId,$savePath,$fname,time(),$v['size']));
							if($res){
								$_SESSION['ucapacity'] = floatval($_SESSION['ucapacity']) + $v['size'];
							}
						}else{
							array_push($stat_arr,array($fname,'err'));
						}
					}
				}
				$tmp_arr['stat'] = $stat_arr;
				exit(json_encode($tmp_arr));
			}
			break;



		//修改密码
		case "changePassword":
			$pwd1 = I('pwd1','p');
			$pwd2 = I('pwd2','p');
			_checkVal($pwd1,$pwd2);//检测变量

			$pdo = MyPdo2::init();
			$sql = 'update user_list set pwd = ? where account = ? and pwd = ?';
			$res = $pdo->dml($sql,array(md5($pwd2),$account,md5($pwd1)));
			if($res){
				$tmp_arr['stat'] = 'ok';
			}else{
				$tmp_arr['stat'] = 'err2';	//修改密码失败
			}
			exit(json_encode($tmp_arr));
			break;


		//获取用户的文件列表
		case '_getDirList':
			$parent = intval(I('parent','p'));

			$pdo = MyPdo2::init();
			$sql = "select id,parent,type,path,fname,ctime,size,share from file_list where account = ?";
			$res = $pdo->dql($sql,array($account));			
			if($res){
				$tmp_arr['data'] = $res;
			}else{
				$tmp_arr['data'] = array();
			}
			$jsonStr = json_encode($tmp_arr);
			$userFileListcachePath = '../cache/user_file_list/'.$account;
			mkdirs(dirname($userFileListcachePath));
			file_put_contents($userFileListcachePath,$jsonStr);
			exit($jsonStr);
			break;



		//创建目录
		case 'createDir':
			$dirName = I('dirName','p');

			if(!_checkChar($dirName)){
				$tmp_arr['stat'] = 'err4';	//非法字符！
				exit(json_encode($tmp_arr));
			}

			$path = I('path','p');

			_checkVal($dirName,$path);//检测变量

			$parent = intval(I('parent','p'));
			$pdo = MyPdo2::init();
			//date('Y-m-d H:i')
			$sql2 = "select id from file_list where account = ? and parent = ? and fname = ?";
			$res2 = $pdo->dql($sql2,array($account,$parent,$dirName));
			if(!$res2){
				$sql = "insert into file_list values(null,?,?,'dir',?,?,?,0,'no')";
				$res = $pdo->dml($sql,array($account,$parent,$path,$dirName,time()));
				if($res){
					$tmp_arr['stat'] = 'ok';	//目录创建成功！
					_deleteFileListCahce($account);	//删除文件列表缓存
				}else{
					$tmp_arr['stat'] = 'err3';	//创建目录失败！
				}
			}else{
				$tmp_arr['stat'] = 'err2';	//目录已存在！
			}
			exit(json_encode($tmp_arr));
			break;



		//激活账号
		case 'register':
			$name = I('name','p');
			$pwd = I('pwd','p');
			_checkVal($name,$pwd);//检测变量
			$pdo = MyPdo2::init();
			$sql = 'select id from user_list where account = ?';
			$res = $pdo->dql($sql,array($account),1);
			if($res){
				$tmp_arr['stat'] = 'err2';	//工号已存在！
			}else{
				$sql2 = 'insert into user_list values(null,?,?,?,1,2,500)';
				$res2 = $pdo->dml($sql2,array($account,$name,md5($pwd)));
				if($res2){
					$tmp_arr['stat'] = 'ok';	//工号激活成功！
				}else{
					$tmp_arr['stat'] = 'err3';	//工号激活异常！
				}
			}
			exit(json_encode($tmp_arr));
			break;


		//登陆
		case 'login':
			$pwd = I('pwd','post');
			_checkVal($pwd,$account);//检测变量
			$pdo = MyPdo2::init();
			$sql = 'select account,name,stat,capacity,ulimit from user_list where account = ? and pwd = ? limit 1';
			$res = $pdo->dql($sql,array($account,md5($pwd)),1);
			if($res){
				//换算成字节
				$res['ulimit2'] = floatval($res['ulimit']) * 1024 * 1024;
				$res['capacity2'] = floatval($res['capacity']) * 1024 * 1024 * 1024;
				$_SESSION['account'] = $res['account'];
				$_SESSION['ulimit'] = $res['ulimit2'];
				$_SESSION['capacity'] = $res['capacity2'];
				$tmp_arr['stat'] = 'ok';
				$tmp_arr['data'] = $res;
			}else{
				$tmp_arr['stat'] = 'err2';
			}
			exit(json_encode($tmp_arr));
			break;



		//退出
		case 'exit':
			session_destroy();
			echo 'ok';
			break;


		
	}





//删除文件列表缓存
function _deleteFileListCahce($account,$type=false){
	if(!$type || $type == 1){
		$cacheFileList = '../cache/user_file_list/'.$account;
		if(file_exists($cacheFileList)){
			unlink($cacheFileList);
		}
	}
	if(!$type || $type == 2){
		$cacheUseCapacity = '../cache/capacity/'.$account;
		if(file_exists($cacheUseCapacity)){
			unlink($cacheUseCapacity);
		}
	}
	if(!$type || $type == 3){
		$cacheShareMe = '../cache/share_me/'.$account;
		if(file_exists($cacheShareMe)){
			unlink($cacheShareMe);
		}
	}
}


